// GoatlistCategory.cs
// 
// Copyright © 2009 FreeZzaph
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace LibFreeZzaph.Goatlist
{
	
	internal abstract class GoatlistCategory : Category
	{	
		private static readonly Regex pageLinkRegex =
			new Regex(@"<a href=""/cgi-bin/atx/out.cgi\?s=\d+&u=([^""]+)"">", RegexOptions.Compiled | RegexOptions.IgnoreCase);
		private static readonly Regex categoryUrlRegex =
			new Regex(@"/(.+?)-(.+?)\..+", RegexOptions.Compiled);
		
		private string categoryUrl;
		
		public GoatlistCategory(string name, string description, string filter, string categoryUrl)
			: base (name, description, filter)
		{
			this.categoryUrl = categoryUrl;
		}
				
		public override sealed IList<Uri> FetchUris(uint start, int count)
		{
			// Construct the "real" category URL
			Match categoryMatch = categoryUrlRegex.Match(categoryUrl);
			string category = categoryMatch.Groups[1].ToString();
			string categoryGroup = categoryMatch.Groups[2].ToString();
			uint page = start / 100; 
			
			uint pageStart = start % 100;
			uint currentCount = 0;
			int realCount = count;
			if (realCount == -1) realCount = 100 - (int)pageStart;
			
			List<Uri> urls = new List<Uri>();
			List<string> duplicateCheck = new List<string>();
			while (currentCount < realCount)
			{
				Uri realCategoryUrl = new Uri(
					string.Format("http://goatlist.com/{0}/{1}-611{2:0000}.php",
						categoryGroup, category, page));
				//Uri realCategoryUrl = new Uri("file:///tmp/wife.html");
			
				string categoryData = FreeZzaphUtility.FetchUrl(realCategoryUrl);
				
				Match match = pageLinkRegex.Match(categoryData);
				while (match.Success && pageStart > 0)
				{
					match = match.NextMatch();
					pageStart--;
				}
				while (match.Success && currentCount < realCount)
				{
					string decodedUrl = Uri.UnescapeDataString(match.Groups[1].ToString());
					
					if (!duplicateCheck.Contains(decodedUrl))
					{
						try
						{
							duplicateCheck.Add(decodedUrl);
							Uri url = new Uri(decodedUrl);
							urls.Add(url);
							currentCount++;
						}
						catch (UriFormatException)
						{
							// Invalid URL
						}
					}
				
					match = match.NextMatch();
				}
				
				page++;
			}
			
			return urls;
		}
	}
}
